<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.word" clearable placeholder="单词" style="width: 140px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.keyword" clearable placeholder="模糊匹配" style="width: 140px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.prefix" clearable placeholder="前缀" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.stem" clearable placeholder="词根" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.suffix" clearable placeholder="后缀" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.sid" clearable placeholder="句子ID" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.realSubWordFreqGt" type="number" clearable placeholder="词频>=" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.realSubWordFreqLt" type="number" clearable placeholder="词频小于" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker
        v-model="qdate"
        type="daterange"
        align="right"
        style="margin-bottom: 10px;vertical-align: middle;"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="downloadExcel">
        导出
      </el-button>
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-warning" @click="doScript">
        执行脚本
      </el-button> -->
      <!-- <router-link :to="'/englishArtifact/word/uploadData'">
        <el-button class="filter-item" style="margin-left: 10px;" type="warning">
          导入
        </el-button>
      </router-link> -->
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="updateAllExSenPreNum">
        生成【例句数量】
      </el-button> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      element-loading-text="玩命拉取中"
      element-loading-spinner="el-icon-loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单词" prop="name" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="全面释义" align="center">
        <template slot-scope="{row}">
          {{ row.completePh }}
        </template>
      </el-table-column>
      <el-table-column label="简明释义" align="center">
        <template slot-scope="{row}">
          <p>{{ row.simplePh }}</p>
        </template>
      </el-table-column>
      <el-table-column label="例句数" prop="ex_sen_num" sortable="custom" align="center" width="100">
        <template slot-scope="{row}">
          <router-link :to="{path: '/englishArtifact/word/exSentence/' + row.id, query: {}}">
            {{ row.exSenPhNum }} / {{ row.exSenNum }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="例句总数" prop="ex_sen_pre_num" sortable="custom" align="center" width="110">
        <template slot-scope="{row}">
          <router-link :to="{path: '/englishArtifact/word/exSentence/' + row.id, query: {}}">
            {{ row.exSenPreNum }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="词频" prop="real_sub_word_freq" sortable="custom" align="center" width="100">
        <template slot-scope="{row}">
          <span>{{ row.realSubWordFreq }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" prop="add_time" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>录入：{{ parseTime(row.addTime) }}</span><br>
          <span>更新：{{ parseTime(row.updateTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="showUpdateDialog(row)">
            修改
          </el-button>
          <el-dropdown>
            <el-button type="primary" size="small">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="goExSentence(row)">例句管理</el-dropdown-item>
              <el-dropdown-item @click.native="deleteMobile(row)">删除记录</el-dropdown-item>
              <el-dropdown-item :disabled="baiduPullLoad" @click.native="baiduPull(row)">百度音标拉取</el-dropdown-item>
              <el-dropdown-item :disabled="youdaoPullLoad" @click.native="youdaoPull(row)">有道音标拉取</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <!--修改mobile-->
    <el-dialog :visible.sync="updateDialog" :title="isAdd ? '新增单词' : '编辑单词'" append-to-body width="920px">
      <el-form ref="form" :model="form" :rules="rules" :inline="false" size="small" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单词：" prop="name">
              <template>
                <el-input v-model="form.name" placeholder="单词" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="拆解：" prop="disassembly">
              <template>
                <el-input v-model="form.disassembly" placeholder="单词拆解，以·分割" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="真题词频：" prop="realSubWordFreq" label-width="100px">
              <template>
                <el-input v-model="form.realSubWordFreq" placeholder="单词真题词频" />
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="全面释义">
          <template>
            <el-input v-model="form.completePh" type="textarea" :autosize="{ minRows: 2, maxRows: 5}" placeholder="全面释义" />
          </template>
        </el-form-item>
        <el-form-item label="简明释义">
          <template>
            <el-input v-model="form.simplePh" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="简明释义" />
          </template>
        </el-form-item>
        <el-form-item label="英文释义">
          <template>
            <el-input v-model="form.engPh" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="英文释义" />
          </template>
        </el-form-item>
        <el-form-item label="形象记忆">
          <template>
            <el-input v-model="form.imagMem" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="形象记忆" />
          </template>
        </el-form-item>
        <el-form-item label="单词笔记">
          <template>
            <el-input v-model="form.note" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="单词笔记" />
          </template>
        </el-form-item>

        <el-divider>词根词缀部分</el-divider>
        <el-form-item label="整体记忆">
          <template>
            <el-input v-model="form.raPh" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="整体记忆" />
          </template>
        </el-form-item>
        <el-row v-for="(item, idx) in form.raList" :key="item.id">
          <el-col :span="5">
            <el-form-item :label="'词根词缀' + (idx + 1)" prop="ra">
              <template>
                <el-input v-model="item.name" placeholder="词根词缀" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="释义" prop="ph">
              <template>
                <el-input v-model="item.ph" clearable placeholder="释义" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="类型" prop="type">
              <template>
                <el-select v-model="item.type" clearable placeholder="类型" class="filter-item" style="width: 120px">
                  <el-option key="1" label="前缀" :value="1" />
                  <el-option key="2" label="词根" :value="2" />
                  <el-option key="3" label="后缀" :value="3" />
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <i @click="addItem(form, idx)" class="el-icon-circle-plus-outline" style="margin-left: 2px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
          <i v-if="idx > 0" @click="removeItem(form, idx)" class="el-icon-remove-outline" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
        </el-row>

        <el-divider>简单例句部分
          <i v-if="showSimpleSentence" class="el-icon-arrow-down" style="cursor:pointer" @click="changeState('showSimpleSentence', true)" />
          <i v-else class="el-icon-arrow-up" style="cursor:pointer" @click="changeState('showSimpleSentence', false)" />
        </el-divider>
        <el-row v-for="(item, idx) in form.simpleSentenceList" :key="item.id" v-show="showSimpleSentence">
          <el-col :span="11">
            <el-form-item :label="'例句' + (idx + 1)" prop="ra">
              <template>
                <el-input v-model="item.content" placeholder="简单例句" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="释义" prop="ph">
              <template>
                <el-input v-model="item.ph" clearable placeholder="释义" />
              </template>
            </el-form-item>
          </el-col>
          <i @click="addSimpleSentenceItem(form, idx)" class="el-icon-circle-plus-outline" style="margin-left: 2px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
          <i @click="removeSimpleSentenceItem(form, idx)" class="el-icon-remove-outline" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
        </el-row>

        <el-divider>单词短语部分
          <i v-if="showPhrase" class="el-icon-arrow-down" style="cursor:pointer" @click="changeState('showPhrase', true)" />
          <i v-else class="el-icon-arrow-up" style="cursor:pointer" @click="changeState('showPhrase', false)" />
        </el-divider>
        <el-row v-for="(item, idx) in form.phraseList" :key="item.id" v-show="showPhrase">
          <el-col :span="11">
            <el-form-item :label="'短语' + (idx + 1)" prop="ra">
              <template>
                <el-input v-model="item.content" placeholder="单词短语" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="释义" prop="ph">
              <template>
                <el-input v-model="item.ph" clearable placeholder="释义" />
              </template>
            </el-form-item>
          </el-col>
          <i @click="addPhraseItem(form, idx)" class="el-icon-circle-plus-outline" style="margin-left: 2px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
          <i @click="removePhraseItem(form, idx)" class="el-icon-remove-outline" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
        </el-row>

        <el-divider>单词其他形式
          <i v-if="showWf" class="el-icon-arrow-down" style="cursor:pointer" @click="changeState('showWf', true)" />
          <i v-else class="el-icon-arrow-up" style="cursor:pointer" @click="changeState('showWf', false)" />
        </el-divider>
        <el-row v-for="(item, idx) in form.formList" :key="item.id" v-show="showWf">
          <el-col :span="11">
            <el-form-item :label="'类型' + (idx + 1)" prop="name">
              <template>
                <el-input v-model="item.name" placeholder="类型" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="值" prop="value">
              <template>
                <el-input v-model="item.value" placeholder="值" />
              </template>
            </el-form-item>
          </el-col>
          <i @click="addFormItem(form, idx)" class="el-icon-circle-plus-outline" style="margin-left: 2px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
          <i @click="removeFormItem(form, idx)" class="el-icon-remove-outline" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
        </el-row>

        <el-divider>单词音标
          <i v-if="showPronounce" class="el-icon-arrow-down" style="cursor:pointer" @click="changeState('showPronounce', true)" />
          <i v-else class="el-icon-arrow-up" style="cursor:pointer" @click="changeState('showPronounce', false)" />
        </el-divider>
        <el-row v-for="(item, idx) in form.pronounceList" :key="item.id" v-show="showPronounce">
          <el-col :span="5">
            <el-form-item :label="'类型' + (idx + 1)" prop="name">
              <template>
                <el-select v-model="item.type" placeholder="类型" class="filter-item" style="width: 100%">
                  <el-option key="1" label="英式" :value="1" />
                  <el-option key="2" label="美式" :value="2" />
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="值" prop="value">
              <template>
                <el-input v-model="item.content" placeholder="值" />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="音频" prop="value">
              <template>
                <el-input v-model="item.audio" placeholder="音频" style="width:90%;float:left" />
                <el-button @click="openBaseUrl(item.audio)" icon="el-icon-link" style="width:10%;float:left" />
              </template>
            </el-form-item>
          </el-col>
          <!-- <i @click="addPhraseItem(form, idx)" class="el-icon-circle-plus-outline" style="margin-left: 2px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
          <i @click="removePhraseItem(form, idx)" class="el-icon-remove-outline" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i> -->
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import edit from './module/edit'
import { getList, save, update, deleteMobile, getRaList, getPhraseList, getSimpleSentenceList, updateAllExSenPreNum,
  getFormList, getPronounceList, downloadExcel, baiduPull, youdaoPull, precisePull } from '@/api/word/word'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: '单词列表',
  components: { Pagination },
  filters: {
  },
  data() {
    return {
      baiduPullLoad: false,
      youdaoPullLoad: false,
      detailDialog: false,
      updateDialog: false,
      wpDialog: false,
      isAdd: true,
      form: {
        changeIntegral: 0,
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '请输入单词', trigger: 'change' }]
      },
      defaultRa: {'id': Math.floor(Math.random()*100000000), name: '', ph: ''},
      defaultPhrase: {'id': null, content: '', ph: ''},
      defaultSimpleSentence: {'id': null, content: '', ph: ''},
      defaultForm: {'id': null, name: '', value: ''},
      defaultPronounce: {'id': null, content: '', ph: ''},
      loading: false,
      syncLoading: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // 查询参数
      listQuery: {
        page: 1,
        size: 10,
        sort: 'update_time',
        order: 'desc'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      supThis: this,
      qdate: [],
      currentUser: {},
      showPhrase: false,
      showSimpleSentence: false,
      showWf: false,
      showPronounce: false
    }
  },
  created() {
    if(this.$route.query.type && this.$route.query.name) {
      if(this.$route.query.type === 1) {
        this.listQuery.prefix = this.$route.query.name
      } else if (this.$route.query.type === 2) {
        this.listQuery.stem = this.$route.query.name
      } else if (this.$route.query.type === 3) {
        this.listQuery.suffix = this.$route.query.name
      }
    }
    this.listQuery.sid = (this.$route.query.sid && this.$route.query.sid > 0) ?  this.$route.query.sid: undefined
    this.getList()
  },
  methods: {
    baiduPull(row) {
      this.baiduPullLoad = true
      this.listLoading = true
      baiduPull(row.id).then(res => {
        this.baiduPullLoad = false
        this.listLoading = false
        if( res.code === 200 ){
          if(res.data.flag){
            this.$message({
              type: 'success',
              message: res.data.msg
            })
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }
      }).catch(e => {
        this.baiduPullLoad = false
        this.listLoading = false
      })

    },
    youdaoPull(row) {
      this.listLoading = true
      this.youdaoPullLoad = true
      youdaoPull(row.id).then(res => {
        this.youdaoPullLoad = false
        this.listLoading = false
        if( res.code === 200 ){
          if(res.data.flag){
            this.$message({
              type: 'success',
              message: res.data.msg
            })
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }
      }).catch(e => {
        this.youdaoPullLoad = false
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      if (this.qdate && this.qdate.length === 2) {
        this.listQuery.startTime = this.qdate[0]
        this.listQuery.endTime = this.qdate[1]
      } else {
        this.listQuery.startTime = this.listQuery.endTime = null
      }
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        if (this.listQuery.word && !this.listQuery.keyword && !this.listQuery.prefix && !this.listQuery.stem && !this.listQuery.suffix && !this.listQuery.sid && !this.listQuery.realSubWordFreqGt && !this.listQuery.realSubWordFreqLt && this.list.length <= 0 ) {
          var data = {
            word : this.listQuery.word
          }
          this.precisePull(data)
        }
        this.listLoading = false
      })
    },
    // 拉取单词
    precisePull(data) {
      this.$confirm('未搜索到单词 '+ data.word +' 是否立即拉取？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        precisePull(data).then((res) => {
          this.listLoading = false
          if (!res.data.wid) {
            this.$notify({
              title: '失败',
              message: '单词拉取失败~',
              type: 'error',
              duration: 2000,
            })
          } else {
            this.$notify({
              title: '成功',
              message: '拉取成功~',
              type: 'success',
              duration: 2000,
            })
            this.getList()
          }
        }).catch((e) => {
          this.listLoading = false
          this.$message.error('操作失败，请稍后重试')
        })
      })
    },
    getRaList(row) {
      getRaList(row.id).then(res => {
        if(res && res.data) {
          var list = res.data
          list.forEach(d => {
            if(d.midline === -1) {
              d.name = ('-' + d.name)
            } else if(d.midline === 1){
              d.name = (d.name + '-')
            } else if(d.midline === 2){
              d.name = ('-' + d.name + '-')
            }
          })
          row.raList = list
        }
        if(!row.raList || row.raList.length == 0) {
          row.raList = [Object.assign({}, this.defaultRa)]
        }
        this.form = Object.assign({}, row)
      }).catch(err=> {
        this.$message({
          type: 'error',
          message: '加载词根词缀失败，请联系管理员!'
        })
        console.log(err)
      });
    },
    getPhraseList(row) {
      getPhraseList(row.id).then(res => {
        if(res && res.data) {
          var list = res.data
          row.phraseList = list
        }
        if(!row.phraseList || row.phraseList.length == 0) {
          row.phraseList = [Object.assign({}, this.defaultPhrase)]
        }
        this.form = Object.assign({}, row)
      }).catch(err=> {
        this.$message({
          type: 'error',
          message: '加载短语失败，请联系管理员!'
        })
        console.log(err)
      });
    },
    getSimpleSentenceList(row) {
      getSimpleSentenceList(row.id).then(res => {
        if(res && res.data) {
          var list = res.data
          row.simpleSentenceList = list
        }
        if(!row.simpleSentenceList || row.simpleSentenceList.length == 0) {
          row.simpleSentenceList = [Object.assign({}, this.defaultSimpleSentence)]
        }
        this.form = Object.assign({}, row)
      }).catch(err=> {
        this.$message({
          type: 'error',
          message: '加载简单例句失败，请联系管理员!'
        })
        console.log(err)
      });
    },
    getFormList(row) {
      getFormList(row.id).then(res => {
        if(res && res.data) {
          var list = res.data
          row.formList = list
        }
        if(!row.formList || row.formList.length == 0) {
          row.formList = [Object.assign({}, this.defaultForm)]
        }
        this.form = Object.assign({}, row)
      }).catch(err=> {
        this.$message({
          type: 'error',
          message: '加载单词其他形式失败，请联系管理员!'
        })
        console.log(err)
      });
    },
    getPronounceList(row) {
      getPronounceList(row.id).then(res => {
        if(res && res.data) {
          var list = res.data
          row.pronounceList = list
        }
        if(!row.pronounceList || row.pronounceList.length == 0) {
          row.pronounceList = [Object.assign({}, this.defaultPronounce)]
        }
        this.form = Object.assign({}, row)
      }).catch(err=> {
        this.$message({
          type: 'error',
          message: '加载单词音标，请联系管理员!'
        })
        console.log(err)
      });
    },
    openBaseUrl(url) {
      if(!url) {
        return this.$message.error('请先填写链接地址')
      }
      window.open(url)
      return
    },
    goExSentence(row) {
      this.$router.push({path: '/english/word/sentence/' + row.id})
    },
    updateAllExSenPreNum() {
      updateAllExSenPreNum().then(res => {
        this.$message({ type: 'success', message: '操作成功!' })
        this.getList()
      }).catch(err => {
        this.$message({ type: 'error', message: '操作失败，请联系管理员!' })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.size = 10
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sort = prop
      if(order === 'ascending'){
        this.listQuery.order = 'asc'
      }else {
        this.listQuery.order = 'desc'
      }
      this.handleFilter()
    },
    showUpdateDialog(row) {
      this.form = Object.assign({}, row)
      this.getRaList(row)
      this.getPhraseList(row)
      this.getSimpleSentenceList(row)
      this.getFormList(row)
      this.getPronounceList(row)
      this.updateDialog = true
      this.isAdd = false

      this.showPhrase = false
      this.showSimpleSentence = false
      this.showWf = false
      this.showPronounce = false
    },
    changeState(filed, value) {
      this[filed] = !value
    },
    addItem(row, idx){
      row.raList.splice(idx+1, 0, Object.assign({}, this.defaultRa))
    },
    removeItem(row, idx) {
      row.raList.splice(idx, 1)
    },
    addPhraseItem(row, idx){
      var phrase = Object.assign({}, this.defaultPhrase)
      phrase.id = Math.floor(Math.random()*100000000)
      row.phraseList.splice(idx+1, 0, phrase)
    },
    removePhraseItem(row, idx) {
      if(row.phraseList.length == 1) {
        return
      }
      row.phraseList.splice(idx, 1)
    },
    addSimpleSentenceItem(row, idx){
      var sentence = Object.assign({}, this.defaultSimpleSentence)
      sentence.id = Math.floor(Math.random()*100000000)
      row.simpleSentenceList.splice(idx+1, 0, sentence)
    },
    removeSimpleSentenceItem(row, idx) {
      if(row.simpleSentenceList.length == 1) {
        return
      }
      row.simpleSentenceList.splice(idx, 1)
    },
    addFormItem(row, idx){
      var form = Object.assign({}, this.defaultForm)
      form.id = Math.floor(Math.random()*100000000)
      row.formList.splice(idx+1, 0, form)
    },
    removeFormItem(row, idx) {
      if(row.formList.length == 1) {
        return
      }
      row.formList.splice(idx, 1)
    },
    handleCreate(row) {
      this.resetForm()
      this.updateDialog = true
      this.isAdd = true
    },
    deleteMobile(row) {
      this.$confirm('确定删除该单词?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMobile(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        })
      }).catch(() => {})
    },
    // 隐藏弹框
    cancel() {
      this.updateDialog = false
      this.wpDialog = false
    },
    // 修改
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          for(var i = 0; i < this.form.raList.length; i++) {
            var ra = this.form.raList[i]
            if(ra.name && (!ra.type || !ra.ph)) {
              this.$message({ type: 'error', message: '请补全词根词缀信息!' })
              return
            }
          }
          this.loading = true
          if (this.form.id) {
            update(this.form).then(res => {
              this.resetForm()
              this.$notify({
                title: '修改成功',
                type: 'success',
                duration: 2500
              })
              this.loading = false
              this.updateDialog = false
              this.getList()
            }).catch(err => {
              this.loading = false
              console.log(err)
            })
          } else {
            save(this.form).then(res => {
              this.resetForm()
              this.$notify({
                title: '新增成功',
                type: 'success',
                duration: 2500
              })
              this.loading = false
              this.updateDialog = false
              this.getList()
            }).catch(err => {
              this.loading = false
              this.$message({
                type: 'error',
                message: err || '删除失败!'
              })
              console.log(err)
            })
          }
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    downloadExcel() {
      this.listLoading = true
      downloadExcel(this.listQuery).then(response => {
        this.download(response)
        this.listLoading = false
      }).catch((e) => {
        console.log(e)
        this.listLoading = false
      })
    },
    download(data) {
      if (!data || !data.data) {
        return
      }
      var blob = new Blob([data.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      var url = window.URL.createObjectURL(blob)
      var aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.href = url
      var fileName = '单词列表-' + new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '.xlsx'
      aLink.setAttribute('download', fileName)
      document.body.appendChild(aLink)
      aLink.click()
      document.body.removeChild(aLink)
      window.URL.revokeObjectURL(url)
    },
    resetForm() {
      this.form = { 'name': undefined, raList: [Object.assign({}, this.defaultRa)] }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // doScript(){
    //   this.$confirm('确定执行单词例句生成脚本?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.listLoading = true
    //     doScript(this.listQuery).then(response => {
    //       this.download(response)
    //       this.listLoading = false
    //     }).catch((e) => {
    //       console.log(e)
    //       this.listLoading = false
    //     })
    //   }).catch(() => {})
    // }
  }
}
</script>
<style>
.question_topic_tree_search{
  width: 200px;
  display: inline-block;
  margin-bottom: 10px;
  vertical-align: middle;
  line-height:35px
}
.row{
  margin-bottom: 20px;
}
</style>

